package com.rui.study.commons.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class BeanUtil {

    public static final Logger LOGGER = LoggerFactory.getLogger(BeanUtil.class);

    public static <T> T buildBean(Map<String, Object> data, Class<T> clazz) {
        T obj = null;
        try {
            obj = clazz.newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
                String property = propertyDescriptor.getName();
                if ("class".equals(property))
                    continue;
                propertyDescriptor.getWriteMethod().invoke(obj, data.get(property));
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return obj;
    }




}
